package com.hp.bon.sgw.ctrl;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.jboss.resteasy.client.ProxyFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.ctrl.SGWController.NodeProcessInf;
import com.hp.bon.sgw.util.Comutils;

public class ControllerConfigService
{
  private static ControllerConfigService instance;
  private static final Logger logger = LoggerFactory.getLogger(ControllerConfigService.class);
  private String CONFIG_File = "./etc/sgw.properties";
  private volatile Map<String, SGWController.NodeProcessInf> sgwInstanceMap = Collections.emptyMap();
  private SGWRemoteInterface sgwRemoteServer;

	public static ControllerConfigService getInstance() {
		if (instance == null) {
			instance = new ControllerConfigService();
			// instance.init();
		}
		return instance;
	}

	public void init(String configFile) {
		CONFIG_File = configFile;
		sgwInstanceMap = this.loadSGWInstance();

	}

  private Map<String, SGWController.NodeProcessInf> loadSGWInstance()
  {
    Map map = new HashMap();
    try {
      Properties properties = Comutils.getPropertiesFromFile(this.CONFIG_File);

      String key = null;

      for (Map.Entry entry : properties.entrySet()) {
        key = (String)entry.getKey();
        if (key.startsWith("process")) {
          String[] value = entry.getValue().toString().split("\\|");
          if ((value != null) && (value.length == 4)) {
            SGWController.NodeProcessInf nodeProcessInf = new SGWController.NodeProcessInf(value[0], value[1], value[2], value[3]);
            map.put(nodeProcessInf.id, nodeProcessInf);

            if ("SGW".equals(nodeProcessInf.processType)) {
              logger.info("SGWRemoteServer:" + nodeProcessInf.managerURL);
              this.sgwRemoteServer = getRemoetIntf(nodeProcessInf.managerURL);
            }
          }
        }
      }
    }
    catch (Exception e) {
      logger.error("load config file failed," + this.CONFIG_File + "," + e.toString());
    }

    return map;
  }

	public Map<String, NodeProcessInf> getInstanceFormFile() {
		return this.loadSGWInstance();
	}

	public Map<String, NodeProcessInf> getSgwInstanceMap() {
		return sgwInstanceMap;
	}

  public SGWRemoteInterface getSgwRemoteServer() {
    return this.sgwRemoteServer;
  }

	private SGWRemoteInterface getRemoetIntf(String nodeURL) {
		return ProxyFactory.create(SGWRemoteInterface.class, nodeURL);
	}

	public void setSgwInstanceMap(Map<String, NodeProcessInf> sgwInstanceMap) {
		this.sgwInstanceMap = sgwInstanceMap;
	}

	public void setCONFIG_File(String cONFIG_File) {
		CONFIG_File = cONFIG_File;
	}

}
